package sms

import (
	"encoding/json"
	"fmt"

	"admin.supervise.limaochuxing.top/config"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v5/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
)

type aliyunService struct {
    client *dysmsapi.Client
}

func NewAliyunService() SMS {
    c, _ := dysmsapi.NewClient(&openapi.Config{
        AccessKeyId:     &config.Config.AliYunAccessKeyId,
        AccessKeySecret: &config.Config.AliYunAccessKeySecret,
        Endpoint:        &config.Config.AliYunDySmsEndPoint,
    })
    return &aliyunService{client: c}
}

func (s *aliyunService) SendLoginCode(phone,code string) (*SmsResp,error) {
    req := &dysmsapi.SendSmsRequest{
        PhoneNumbers:  &phone,
        SignName:      &config.Config.SmsSignName,
        TemplateCode:  &config.Config.AliYunLoginTemplateCode,
        TemplateParam: toTemplateParam(map[string]string{"code":code}),
    }
     resp, err := s.client.SendSmsWithOptions(req, &util.RuntimeOptions{})
     if err != nil {
         return nil,err
     }
     res,_:=json.Marshal(resp.Body)
     fmt.Println(string(res))
     return &SmsResp{
        Data: string(res),
     },nil
}

func toTemplateParam(params map[string]string) *string {
    jsonByte, _ := json.Marshal(params)
    jsonStr := string(jsonByte)
    return &jsonStr
}